package sunhapper.me.dagger2.activity;

import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;

import javax.inject.Inject;

import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
import sunhapper.me.dagger2.mvvm.factory.ViewModelFactory;

/**
 * Created by sunhapper(haipeng.sun3@56qq.com) on 2018/8/17 .
 */
abstract class BaseActivity<VM extends ViewModel> extends AppCompatActivity implements HasSupportFragmentInjector {

    @Inject
    ViewModelFactory mViewModelFactory;
    protected VM mViewModel;

    @Inject
    DispatchingAndroidInjector<Fragment> dispatchingAndroidInjector;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        mViewModel = createViewModel();
        super.onCreate(savedInstanceState);
    }

    protected abstract VM createViewModel();

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return dispatchingAndroidInjector;
    }

    public <T extends ViewModel> T getViewModel(@NonNull Class<T> modelClass) {
        return getViewModel(modelClass, mViewModelFactory);
    }

    public <T extends ViewModel> T getViewModel(@NonNull Class<T> modelClass,
            @Nullable ViewModelProvider.Factory factory) {
        return ViewModelProviders.of(this, factory).get(modelClass);
    }
}
